package com.hx.demo.controller;


import cn.hutool.core.util.ObjectUtil;
import com.hx.demo.domain.User;
import com.hx.demo.service.IUserSeervice;
import com.hx.demo.util.AjaxResult;
import com.hx.demo.util.UserCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Controller
public class LoginController {



    @Autowired
    private IUserSeervice userSeervice;



    @GetMapping("/toLogin")
    public String login(){
        return "/login";
    }


    @PostMapping("/loginBody")
    @ResponseBody
    public AjaxResult login(HttpServletRequest request,String username, String password, String captcha, String rememberMe){

        //TODO 检查验证码是否正确

        //判断用户名是否存在
        User userFlag = userSeervice.selectByUserName(username);
        if (ObjectUtil.isNull(userFlag)){
            return AjaxResult.error("该用户不存在,请先注册");
        }

        if (!userFlag.getPassword().equals(password)){
            return AjaxResult.error("用户或者密码不正确");
        }

        //登录成功,记录用户登录的信息，缓存
        String sessionId = request.getSession().getId();
        log.info("SessionId是【{}】",sessionId);
        UserCacheUtil.addUser(sessionId,userFlag);

        return AjaxResult.success();
    }


}
